import Vue from "vue";

import App from "./App.vue";
// import List from './pages/list'

import router from "./router";
import {
  Modal,
  Form,
  Input,
  Button,
  Checkbox,
  Layout,
  Menu,
  Icon,
  Select
} from "ant-design-vue";
import { get } from "./utils/request";
import eventBusPlugin from "./utils/eventStoreBus";
import loaddingPlugin from "./plugins/loadingPlugin";

import "ant-design-vue/dist/antd.css";

Vue.use(Modal);
Vue.use(Form);
Vue.use(Input);
Vue.use(Button);
Vue.use(Checkbox);
Vue.use(Layout);
Vue.use(Menu);
Vue.use(Icon);
Vue.use(Select);
// 注册了公用的事件仓库 - 唯一的单例
Vue.use(eventBusPlugin);
// Vue.use(message);
Vue.use(loaddingPlugin);

// vue.use (obj|fn)  obj : { install: (Vue)=>{}

router.beforeEach((_to, _from, next) => {
  console.log("-beforeEach-");
  // 校验token
  const token = localStorage.getItem("login_token");
  if (token) {
    // 如果有token的话，就不跳转到登录页了
    next();
  } else {
    // 如果没有token的话
    const { href, origin, pathname } = location;
    const writeRouters = ['/login', '/register'];
    if (writeRouters.includes(pathname)) {  
      // 如果本身就在login/register页，就不用做什么了
      next();
    } else {
      // 否则，重定向到login页面;
      location.href = `${origin}/login?callback=${href.replace(origin, "")}`;
    }
  }
});

Vue.config.productionTip = false;

window.addEventListener("load", () => {
  // 验证public key
  if (!localStorage.getItem("public_key")) {
    get("/getPublicKey").then((data) => {
      localStorage.setItem("public_key", data);
    });
  }
  // 验证是否已经登录过
});

new Vue({
  router,
  render: (createElement) => createElement(App),
}).$mount("#app");
